package com.rocksea.app;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.rocksea.app.utils.FileHelper;
import com.rocksea.app.utils.UiUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by 吴志华 on 2017/10/19.
 *
 */

public class CrashHandler implements Thread.UncaughtExceptionHandler
{
    /**
     * 系统默认UncaughtExceptionHandler
     */
    private Thread.UncaughtExceptionHandler mDefaultHandler;

    private Map<String,String> paramsMap = new HashMap<>();
    private Context context;

    public void init(Context context)
    {
        this.context = context;
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e)
    {
        if (!handleException(e)&&mDefaultHandler!=null)
        {
            mDefaultHandler.uncaughtException(t,e);
        }else
        {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(1);

    }

    private boolean handleException(Throwable ex)
    {
        if (ex == null)
        {
            return false;
        }
        collectDeviceInfo(context);
        saveCrashInfo2File(ex);
        return true;
    }

    public void collectDeviceInfo(Context ctx) {
        //获取versionName,versionCode
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                paramsMap.put("versionName", versionName);
                paramsMap.put("versionCode", versionCode);
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.e("CrashHandler", "an error occured when collect package info", e);
        }
        //获取所有系统信息
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                paramsMap.put(field.getName(), field.get(null).toString());
            } catch (Exception e) {
                Log.e("CrashHandler", "an error occured when collect crash info", e);
            }
        }
    }

    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
    private String saveCrashInfo2File(Throwable ex) {

        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : paramsMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        sb.append(result).append("\n");
        try
        {
            String time = format.format(new Date());
            String fileName = "crash-" + time + "-" + ".log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            {
                FileHelper fileHelper = new FileHelper();
                fileHelper.wirteCrash(fileName,sb.toString());
            }
            return fileName;
        }
        catch (Exception e)
        {
            Log.e("CrashHandler", "an error occured while writing file...", e);
        }
        return null;
    }
}
